package com.llyb.tingshu.order.receiver;

import com.llyb.tingshu.common.rabbit.constant.MqConst;
import com.llyb.tingshu.order.service.OrderInfoService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;

@Component
@Slf4j
public class OrderReciever {

    @Autowired
    private OrderInfoService orderInfoService;

    /**
     * 监听订单支付成功消息
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_ORDER_PAY_SUCCESS,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_ORDER),
            key = MqConst.ROUTING_ORDER_PAY_SUCCESS
    ))
    public void orderPaySuccess(String orderNo, Message message, Channel channel) {
        try {
            if (!StringUtils.isEmpty(orderNo)) {
                orderInfoService.orderPaySuccess(orderNo);
            }
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
        }
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            log.error(e.getMessage(),e);
        }
    }

    /**
     * 监听取消订单消息(15 分钟未支付就修改状态)
     * @param orderId
     * @param message
     * @param channel
     */
    @RabbitListener(queues = MqConst.QUEUE_CANCEL_ORDER)
    public void cancelOrder(String orderId, Message message, Channel channel) {

        try {
            if (!StringUtils.isEmpty(orderId)) {
                log.info("收到取消订单消息：{}",orderId);
                orderInfoService.orderCancel(orderId);
            }
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            log.error(e.getMessage(),e);
        }
    }
}
